/*
 *	Cross platform support
 *
 *	Copyright (C) 2011 XiaoJSoft Studio. All Rights Reserved.
 *	Copyright (C) Ji WenCong <whs_jwc@163.com>
 *
 *	kasprintf (copied & modified from Linux Kernel):
 *	Copyright (C) Linus Torvalds <torvalds@klaava.Helsinki.Fi>
 *
 *	This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU General Public License
 *	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "../include/cross.h"

/*
 *	int kasprintf(char **buf,  const char *fmt, ...);
 *
 *	The functions kasprintf() are analogs of sprintf(), except that they allocate a string 
 *	large enough to hold the output including the terminating null byte, and return a pointer 
 *	to it via the first argument. This pointer should be passed to free() to release the 
 *	allocated storage when it is no longer needed.
 */
int kasprintf(char **buf,  const char *fmt, ...)
{
	va_list ap;
	unsigned int len;
	char *p;

	va_start(ap, fmt);
	len = vsnprintf(NULL, 0, fmt, ap);
	va_end(ap);

	p = malloc(len+1);
	if (!p) {
		return(-1);
	}

	va_start(ap, fmt);
	vsnprintf(p, len+1, fmt, ap);
	va_end(ap);

	*buf = p;

	return(len);
}

